<?php

namespace App\Observers;

use App\Repository\WechatWork;
use App\WechatLink;

class WechatLinkObserver
{
    protected $wechatWork;
    public function __construct(WechatWork  $wechatWork)
    {
        $this->wechatWork=$wechatWork;
    }

    /**
     * Handle the wechat link "created" event.
     *
     * @param  \App\WechatLink  $wechatLink
     * @return void
     */
    public function created(WechatLink $wechatLink)
    {

       $result= $this->wechatWork->createExternalContact($wechatLink->name,$wechatLink->user_ids);
       if (isset($result['errcode'])&&$result['errcode']==0){
           $wechatLink->url=$result['link']['url'];
           $wechatLink->wechat_link_id=$result['link']['link_id'];
           $wechatLink->save();
       }else{
           $wechatLink->delete();
           throw new \Exception($result['errmsg']);
       }
    }

    /**
     * Handle the wechat link "updated" event.
     *
     * @param  \App\WechatLink  $wechatLink
     * @return void
     */
    public function updated(WechatLink $wechatLink)
    {
        $result= $this->wechatWork->updateExternalContact($wechatLink->name,$wechatLink->user_ids,$wechatLink->wechat_link_id);


    }

    /**
     * Handle the wechat link "deleted" event.
     *
     * @param  \App\WechatLink  $wechatLink
     * @return void
     */
    public function deleted(WechatLink $wechatLink)
    {
        $this->wechatWork->deleteExternalContact($wechatLink->wechat_link_id);
    }

    /**
     * Handle the wechat link "restored" event.
     *
     * @param  \App\WechatLink  $wechatLink
     * @return void
     */
    public function restored(WechatLink $wechatLink)
    {
        //
    }

    /**
     * Handle the wechat link "force deleted" event.
     *
     * @param  \App\WechatLink  $wechatLink
     * @return void
     */
    public function forceDeleted(WechatLink $wechatLink)
    {
        //
    }
}
